import traceback

import pandas as pd
from flask import Flask, request
from nb_log import get_logger

logger = get_logger(None)
app = Flask(__name__)

import lightgbm as lgb
import numpy as np

model = lgb.Booster(model_file='model_files/lgb_model_third_v1.txt')
flist = model.feature_name()

def prob2score(prob):
    return round(550 - 60 / np.log(2) * np.log(prob / (1 - prob)), 0)

@app.route("/api/<path:model_name>", methods=["POST"])
def api(model_name):
    request_json = request.get_json()
    creditfeature_v3_dict = request_json['third_feature']['creditfeature_v3']
    # idinquiries_v4_dict = request_json['third_feature']['idinquiries_v4']
    # phoneinquiries_v4_dict = request_json['third_feature']['phoneinquiries_v4']
    try:
        df = pd.json_normalize(creditfeature_v3_dict)
        df['prob'] = model.predict(df[flist])
        df['score'] = df['prob'].map(prob2score)
        df[flist] = df[flist].fillna(-999).astype(float)

        prob = df['prob'].iloc[0]
        score = df['score'].iloc[0]

        monitor_features = df[flist].to_dict(orient='records')[0]
        monitor_features['third_prob_v1'] = float(prob)

        monitor_features['third_score_v1'] = score
        return  {"code": 200,
                 "data": {'third_prob_v1': prob,
                         'third_score_v1': score},
                 'monitor_features': monitor_features }
    except:

        return  {"code": 200,
                 "data": {'third_prob_v1': -999,
                         'third_score_v1': -999},
                 'monitor_features': {
                     'err_mes': traceback.format_exc()
                  }}

if __name__ == '__main__':
    app.run(debug=False,host='0.0.0.0',port=8090)

